//
//  QuickScanViewController.m
//  FKGW
//
//  Created by song ce on 2017/2/18.
//  Copyright © 2017年 song ce. All rights reserved.
//

#import "QuickScanViewController.h"
#import "SelecedViewController.h"
#import "AppDelegate.h"
#import "QuickScanCollectionView.h"
#import "LoginViewController.h"
#import "OSSHelper.h"

@interface QuickScanViewController ()
@property (weak, nonatomic) IBOutlet UIButton *collectBtn;
@property (weak, nonatomic) IBOutlet UIButton *deleteBtn;

@property (weak, nonatomic) IBOutlet UIView *scanView;
@property (weak, nonatomic) IBOutlet UIView *buttonView;
@property(nonatomic,strong)QuickScanCollectionView *scanV;
@property(nonatomic,strong)NSMutableArray *dataSouce;
@property(nonatomic,assign)int  currentIndex;
@end

@implementation QuickScanViewController
-(instancetype)init{
    self = [super init];
    if(self){
        [[NSNotificationCenter defaultCenter] postNotificationName:@"regiserNoti" object:nil];
        //监听滑动页数
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(currentPage:) name:@"currentPage" object:nil];
       
    }
    return self;
}

//快速浏览时发来的当前页码。与数组下标一致
- (void)currentPage:(NSNotification *)noti{
    //当前显示的图片在数组当中的下标，用于收藏操作数据
    self.currentIndex = [noti.object  intValue];
    DLog(@"当前页码%d",self.currentIndex);
    //设置收藏按钮的状态
    [self setCollectionBtnStatusWithModel:self.dataSouce[self.currentIndex]];
    
    QickScanModel *model = self.dataSouce[self.currentIndex];
    self.vcName = [NSString stringWithFormat:@"￥ %@",model.price];
    self.titlelabel.textColor = [UIColor whiteColor];
}
//设置收藏按钮的状态
-(void)setCollectionBtnStatusWithModel:(QickScanModel*)item{
    if(item.isCollection){
         [self.collectBtn setImage:[UIImage imageNamed:@"s_icon_shoucang_sel"] forState:UIControlStateNormal];
    }else{
      [self.collectBtn setImage:[UIImage imageNamed:@"button_xihuan_nor"] forState:UIControlStateNormal];
    }
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter ]removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self.naviBar removeFromSuperview];
    self.currentIndex = 0;
    self.buttonView.backgroundColor=[UIColor blackColor];
    QuickScanCollectionView *scanV = [[QuickScanCollectionView alloc]initWithFrame:CGRectMake(0, kNaviBarHeight, Main_Screen_Width, Main_Screen_Height-kNaviBarHeight-99)];
    self.scanV = scanV;
    scanV.count = self.count;
    [self.scanView addSubview:scanV];
    DLog(@"%f",self.scanView.height);
    //真实测试时候第一次加载一张 
    [self loadData:@"1" loadMore:NO];
    [self.view bringSubviewToFront:self.buttonView];
        //删除到最后一张了 留一张吧
    __weak typeof(self) weakSelf = self;
    scanV.lastOnePhotoBlock = ^{
        weakSelf.deleteBtn.enabled = NO;
    };
    //更新数据源
    scanV.updataDataSourceBlock = ^(NSMutableArray *dataSource){
        weakSelf.dataSouce = dataSource;
        QickScanModel *model = weakSelf.dataSouce.firstObject;
        weakSelf.vcName = [NSString stringWithFormat:@"￥ %@",model.price];
        weakSelf.titlelabel.textColor = [UIColor whiteColor];
        
    };
    scanV.loadMoreBlock = ^{
        [weakSelf loadData:@"20" loadMore:YES];
    };
    
      [self.view bringSubviewToFront:self.naviBar];
}

-(void)loadData:(NSString*)size loadMore:(BOOL)loadMore{
    //2．2 推荐商品接口
    NSString *uid = [AppDelegate appDealegate].uid;
    NSString *uidStr;       //用户标识（可为null，不为null时，则根据用户常用搜索项展示）
    if(uid.length){
        uidStr = uid;
    }else{
        uidStr = @"";
    }
    NSDictionary *paraDic = @{
                              @"uid":uidStr,
                              @"size":size
                              };
     __weak typeof(self)  weakSelf = self;
     [Tools AFNetworkingRequestTypePostWithUrl:RECOMMENDGOODS paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
         DLog(@"推荐商品--%@",resultDic);
         if([resultDic[@"flag"] isEqualToString:@"true"]){
             NSArray *dataArr = resultDic[@"data"];
             if([dataArr isKindOfClass:[NSNull class]]) return;
             NSMutableArray *pics = [NSMutableArray array];
             for(NSDictionary *dic in dataArr){
                 //将没有图片的过滤掉
                 if([dic[@"pic"] containsString:@"."]&&![dic[@"pic"] containsString:@"banner"]){
                 QickScanModel *model = [[QickScanModel alloc]init];
                 model.pic = dic[@"pic"];
                 model.price =[NSString stringWithFormat:@"%@",dic[@"price"]];
                 model.pid = dic[@"pid"];
                 model.isCollection = NO;
                model.isNeedPriceLabel = YES;
                 [pics addObject:model];
                }
            }
             if(loadMore){
                 [pics removeObjectAtIndex:0];
             }
             weakSelf.scanV.dataArr = pics;
         }else{
             if(resultDic[@"errorString"]){
                 [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
             }
         }
     }];
}

//删除。从本地列表删除一张图片
- (IBAction)close:(UIButton *)sender {
    [[NSNotificationCenter defaultCenter]postNotificationName:@"deleteOnePhoto" object:nil];
}

//进入首页按钮
- (IBAction)home:(UIButton *)sender {
    //移除快速浏览图片
    [self removeAllQuickScanLocalImage];
    SelecedViewController *selectedViewConteroller = [[SelecedViewController alloc]init];
    BaseNavigationViewController *navi = [[BaseNavigationViewController alloc]initWithRootViewController:selectedViewConteroller];
    [[AppDelegate appDealegate].window setRootViewController:navi];
}

//删除本地的快速浏览缓存
-(void)removeAllQuickScanLocalImage{
    NSString *path=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/QuickScanPhotos"];
    BOOL success=   [[NSFileManager defaultManager]removeItemAtPath:path error:nil];
    if(success){
        DLog(@"正在全部删除---删除成功");
    }
}

//收藏按钮
- (IBAction)collection:(UIButton *)sender {
     //2.3 收藏商品接口
    if(!USERID.length){ //跳转到登录页面
        LoginViewController *login = [[LoginViewController alloc]init];
        login.isModel = YES;
        BaseNavigationViewController *baseNavi = [[BaseNavigationViewController alloc]initWithRootViewController:login];
        [self presentViewController:baseNavi animated:YES completion:nil];
        return;
    }
    
    QickScanModel *model = self.dataSouce[self.currentIndex];
    NSString *pid = model.pid;
    NSString *url ;
    NSDictionary *paraDic;
    if(model.isCollection){//已经收藏  调用取消收藏接口
        paraDic = @{
                    @"userId":USERID,
                    @"productId":pid
                    };
        
        url = DELETECOLLECTION;
        [self  disCollectionWithParam:paraDic url:url];
    }else{//未收藏 调用收藏接口
        paraDic = @{
                    @"uid":USERID,
                    @"pid":pid
                    };
        
        url = COLLECTIONGOODS;
        [self  collectionWithParam:paraDic url:url];
    }
}

//收藏接口
-(void)collectionWithParam:(NSDictionary*)prama  url:(NSString*)url{
    __weak typeof(self)  weakSelf = self;
    [Tools AFNetworkingRequestTypePostWithUrl:url paramters:prama  afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"收藏商品接口--%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSDictionary *dataDic = resultDic[@"data"];
            if([dataDic isKindOfClass:[NSNull class]])return ;
            if([dataDic[@"status"] isEqualToString:@"true"]){//收藏成功
                [MBProgressHUD showTipMessageInWindow:@"收藏成功"];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.collectBtn setImage:[UIImage imageNamed:@"s_icon_shoucang_sel"] forState:UIControlStateNormal];
                    QickScanModel *model = self.dataSouce[self.currentIndex];
                    model.isCollection = YES;
                    self.scanV.dataSoure = self.dataSouce;
                });
            }else{
                if(dataDic[@"errorString"]){
                    [MBProgressHUD showTipMessageInWindow:dataDic[@"errorString"]];
                }
            }
        }else{
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}

//取消收藏接口
-(void)disCollectionWithParam:(NSDictionary*)prama  url:(NSString*)url{
      __weak typeof(self)  weakSelf = self;
    [Tools AFNetworkingRequestTypePostWithUrl:url paramters:prama  afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"取消收藏商品接口--%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSDictionary *dataDic = resultDic[@"data"];
                if([dataDic isKindOfClass:[NSNull class]])return ;
                if([dataDic[@"status"] isEqualToString:@"true"]){//取消收藏成功
                    [MBProgressHUD showTipMessageInWindow:@"取消收藏成功"];
                    //回到主线程
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf.collectBtn setImage:[UIImage imageNamed:@"button_xihuan_nor"] forState:UIControlStateNormal];
                        QickScanModel *model = self.dataSouce[self.currentIndex];
                        model.isCollection = NO;
                        self.scanV.dataSoure = self.dataSouce;
                    });
                }else{
                    if(dataDic[@"errorString"]){
                        [MBProgressHUD showTipMessageInWindow:dataDic[@"errorString"]];
                    }
                }
        }else{
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
